<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>发票登记</title>
        <% include("/common/common_css_js.html"){} %>
    </head>
    <body>
        <% if(so.hasPermission("invoiceAdd:save")){%>
            <a class="mini-button" iconCls="icon-save" onclick="saveInvoice()">保存</a>
        <% } %>
        <div id="invoiceForm" style="margin-top: 5px;padding-bottom: 5px;" class="mini-fit">
            <span>发货人:</span>
            <div id="deliveryCustomerId" name="deliveryCustomerId"
                 class="mini-combobox"
                 style="width:600px;"
                 popupWidth="800" textField="name" valueField="id"
                 allowInput="true" required="true" requiredErrorText="发货人不能为空"
                 emptyText="发货人名称"  onvaluechanged="deliveryCustomerIdChange">
                <div property="columns">
                    <div header="发货人名称" field="name"></div>
                    <div header="发货人简称" field="shortName"></div>
                    <div header="发货人电话" field="phone"></div>
                    <div header="发货人地址" field="address"></div>
                </div>
            </div>

            <div style="margin-top: 5px"></div>
            <span>分单列表:</span>
            <a id="addBtn" class="mini-button" iconCls="icon-add" onclick="showSelectNativeBillPanel()" enabled="false">选择分单</a>
            <a id="removeBtn" class="mini-button" iconCls="icon-remove" onclick="removeNativeBill()" enabled="false">剔除</a>
            <div style="margin-top: 5px"></div>
            <div id="selectedBillDatagrid" class="mini-datagrid" style="width:100%;height:400px;"
                 idField="id"
                 showPager="false"
                 allowCellSelect="true" multiSelect="true"
                 showGroupsSummary="true" showSummaryRow="true" summaryPosition="bottom"
                 ondrawsummarycell="summaryRight">
                <div property="columns">
                    <div type="checkcolumn"></div>
                    <div field="id" headerAlign="center" align="center"  width="140" >分单号</div>
                    <div field="attributionDepartmentId" width="140" headerAlign="center" align="center" allowSort="false" data-options='{cacheName:"department"}' renderer="commonRender">归属部门</div>
                    <div field="deliveryCustomerName" width="140" headerAlign="center" align="center" allowSort="true">发货人名称</div>
                    <div field="totalNumber" width="140" headerAlign="center" align="right" summaryType="sum">总件数</div>
                    <div field="actualWeight" width="140" headerAlign="center" align="right" allowSort="false" renderer="public_moneyRenderer" summaryType="sum">实际重量</div>
                    <div field="chargeableWeight" width="140" headerAlign="center" align="right" allowSort="false" renderer="public_moneyRenderer" summaryType="sum">计费重量</div>
                    <div field="volume" width="140" headerAlign="center" align="right" allowSort="false" renderer="public_moneyRenderer" summaryType="sum">体积</div>
                    <div field="transportCost" width="140" headerAlign="center" align="right" allowSort="false" renderer="public_moneyRenderer" summaryType="sum">运费合计</div>
                    <div field="totalAmount" width="140" headerAlign="center" align="right" allowSort="false" renderer="public_moneyRenderer" summaryType="sum">总金额</div>
                    <div field="actualAmount" width="140" headerAlign="center" align="right" allowSort="false" renderer="public_moneyRenderer" summaryType="sum">实收金额</div>
                    <div field="dropAmount" width="140" headerAlign="center" align="right" allowSort="false" renderer="public_moneyRenderer" summaryType="sum">调整金额(拉货)</div>
                    <div field="settlementAmount" width="140" headerAlign="center" align="right" allowSort="false" renderer="public_moneyRenderer" summaryType="sum">结算金额</div>
<!--                    <div field="cashierId" width="140" headerAlign="center" align="center" allowSort="false" data-options='{cacheName:"sysUser"}' renderer="commonRender">收银员</div>-->
                    <div field="openBillUserId" width="140" headerAlign="center" align="center" allowSort="false" data-options='{cacheName:"sysUser"}' renderer="commonRender">开单人</div>
                    <div field="openBillDate" width="140" headerAlign="center" align="center" allowSort="false" dateFormat="yyyy-MM-dd HH:mm:ss" renderer="ondayRenderer">开单日期</div>
                </div>
            </div>

            <div style="margin-top: 5px"></div>
            <span>开票总金额:</span>
            <input id="invoiceAmount" name="invoiceAmount" emptyText="开票总金额"  class="mini-textbox" vtype="float" value="0" required="true" requiredErrorText="开票总金额不能为空" />

            <span>开票公司:</span>
            <input id="openInvoiceCompanyId" name="openInvoiceCompanyId" class="mini-combobox" style="width:400px;" textField="name" valueField="id" emptyText="请选择..."
                   required="true" allowInput="false" showNullItem="true" nullItemText="请选择..." requiredErrorText="没有选择开票公司"/>

            <div style="margin-top: 5px"></div>
            <span>发票抬头:</span>
            <div id="customerInvoiceId" name="customerInvoiceId"
                 class="mini-combobox"
                 style="width:600px;"
                 popupWidth="1000" textField="invoiceTitle" valueField="id"
                 allowInput="true" required="true" requiredErrorText="发票抬头不能为空"
                 onvaluechanged="customerInvoiceIdChange"
                 emptyText="发票抬头">
                <div property="columns">
                    <div header="发票抬头" field="invoiceTitle"></div>
                    <div header="纳税人识别号" field="taxpayerIdentificationNumber"></div>
                    <div header="电话" field="phoneNumber"></div>
                    <div header="地址" field="invoiceAddress"></div>
                    <div header="开户银行" field="openAccountBankId" data-options='{cacheName:"bank"}' renderer="commonRender"></div>
                    <div header="银行账号" field="bankAccount"></div>
                    <div header="发票类型" field="invoiceTypeId" data-options='{cacheName:"sysDic"}' renderer="commonRender"></div>
                    <div header="税率" field="rateId" data-options='{cacheName:"sysDic"}' renderer="commonRender"></div>
                    <div header="收件人" field="recipientName"></div>
                    <div header="收件人电话" field="recipientPhone"></div>
                    <div header="收件人地址" field="recipientAddress"></div>
                </div>
            </div>

            <input id="invoiceTitle" name="invoiceTitle"  emptyText="发票抬头"  class="mini-hidden" required="true" requiredErrorText="发票抬头不能为空" />

            <div style="margin-top: 5px"></div>
            <span>纳税人识别号:</span>
            <input id="taxpayerIdentificationNumber" name="taxpayerIdentificationNumber" emptyText="纳税人识别号" style="width: 300px"  class="mini-textbox" required="true" requiredErrorText="纳税人识别号不能为空" />

            <div style="margin-top: 5px"></div>
            <span>电话:</span>
            <input id="phoneNumber" name="phoneNumber" emptyText="电话" style="width: 300px"  class="mini-textbox" required="true" requiredErrorText="电话不能为空" />

            <span>地址:</span>
            <input id="invoiceAddress" name="invoiceAddress" emptyText="地址" style="width: 300px"  class="mini-textbox" required="true" requiredErrorText="地址不能为空" />

            <div style="margin-top: 5px"></div>
            <span>开户银行:</span>
            <input id="openAccountBankId" name="openAccountBankId" class="mini-combobox"  textField="name" valueField="id" emptyText="请选择开户银行..."
                   style="width: 300px"  required="false" allowInput="true" showNullItem="true" nullItemText="开户银行..." requiredErrorText="开户银行"/>

            <span>银行账号:</span>
            <input id="bankAccount" name="bankAccount" emptyText="银行账号" style="width: 300px"  class="mini-textbox" required="true" requiredErrorText="银行账号不能为空" />

            <div style="margin-top: 5px"></div>
            <span>发票类型:</span>
            <input id="invoiceTypeId" name="invoiceTypeId" class="mini-combobox" style="width:300px;" textField="name" valueField="id" emptyText="请选择发票类型..."
                   required="false" allowInput="true" showNullItem="true" nullItemText="发票类型..." requiredErrorText="没有选择发票类型"/>
            <span>税率:</span>
            <input id="rateId" name="rateId" class="mini-combobox" style="width:300px;" textField="name" valueField="id" emptyText="请选择税率..."
                   required="false" allowInput="true" showNullItem="true" nullItemText="税率..." requiredErrorText="没有选择税率"/>

            <div style="margin-top: 5px"></div>
            <span>收件人:</span>
            <input id="recipientName" name="recipientName" emptyText="收件人" style="width: 200px"  class="mini-textbox" required="false" requiredErrorText="收件人不能为空" />
            <span>电话:</span>
            <input id="recipientPhone" name="recipientPhone" emptyText="收件人电话" style="width: 200px"  class="mini-textbox" required="false" requiredErrorText="收件人电话不能为空" />
            <span>地址:</span>
            <input id="recipientAddress" name="recipientAddress" emptyText="收件人地址" style="width: 300px"  class="mini-textbox" required="false" requiredErrorText="收件人地址不能为空" />


        </div>


        <!--分单选择-->
        <div id="billSelectPanel" class="mini-window" title="发票分单选择" style="width:1400px;height:700px;"
             showMaxButton="true" showCollapseButton="false" showMinButton="true" showShadow="true"
             showToolbar="true" showFooter="true" showModal="true" allowResize="true" allowDrag="true">
            <div property="footer" style="padding:10px;text-align: right">
                <a  class="mini-button" iconCls="icon-save" onclick="saveSelect()">选择</a>
                <a  class="mini-button" iconCls="icon-close" onclick="public_onCancel('billSelectPanel')">关闭</a>
            </div>

            <div id="queryForm">
                <input id="keyDeliveryCustomerId" name="keyDeliveryCustomerId"  emptyText="客户ID"  class="mini-hidden" requiredErrorText="客户ID不能为空" />
                <span>发货人名称:</span>
                <input id="keyDeliveryCustomerName" name="keyDeliveryCustomerName"  emptyText="发货人名称"  style="width: 600px" class="mini-textbox" enabled="false" requiredErrorText="发货人名称不能为空" />
                <div style="margin-top: 5px"></div>
                <span>分单号：</span>
                <input id="keyBillCode" name="keyBillCode" emptyText="请输入分单号"  class="mini-textbox" selectOnFocus="true" required="false" requiredErrorText="分单号不能为空" />
                <span>开单日期：</span>
                <input id="keyOpenBillStartDate" name="keyOpenBillStartDate"  class="mini-datepicker"   format="yyyy-MM-dd"/>--<input id="keyOpenBillEndDate" name="keyOpenBillEndDate" class="mini-datepicker"  format="yyyy-MM-dd"/>

                <a class="mini-button" iconCls="icon-search" onclick="searchBill()">查询</a>

            </div>

            <div style="margin-top: 5px"></div>

            <div class = "mini-fit">
                <div id="datagrid1" class="mini-datagrid"
                     style="width: 100%; height: 100%;"
                     url="${base}/pages/native_bill_manage/queryBill" idField="id"
                     showPager="true" pageSize="20" sizeList="[10,20,30,50,100,300,500,1000,2000]"
                     multiSelect = "true" allowResize="true"
                     showGroupsSummary="true" showSummaryRow="true" summaryPosition="bottom"
                     allowSortColumn = "true"
                     sortField="createTime"
                     sortOrder="desc">
                    <div property="columns">
                        <div type="checkcolumn" ></div>
                        <div field="id" width="140" headerAlign="center" align="left" allowSort="true">分单号</div>
                        <div field="attributionDepartmentId" width="140" headerAlign="center" align="center" allowSort="false" data-options='{cacheName:"department"}' renderer="commonRender">归属部门</div>
                        <div field="deliveryCustomerName" width="140" headerAlign="center" align="center" allowSort="true">发货人名称</div>
                        <div field="totalNumber" width="140" headerAlign="center" align="right" allowSort="false">总件数</div>
                        <div field="actualWeight" width="140" headerAlign="center" align="right" allowSort="false" renderer="public_moneyRenderer">实际重量</div>
                        <div field="chargeableWeight" width="140" headerAlign="center" align="right" allowSort="false" renderer="public_moneyRenderer">计费重量</div>
                        <div field="volume" width="140" headerAlign="center" align="right" allowSort="false" renderer="public_moneyRenderer">体积</div>
                        <div field="ticketPrice" width="140" headerAlign="center" align="right" allowSort="false" renderer="public_moneyRenderer">起票价</div>
                        <div field="transportCost" width="140" headerAlign="center" align="right" allowSort="false" renderer="public_moneyRenderer">运费合计</div>
                        <div field="totalAmount" width="140" headerAlign="center" align="right" allowSort="false" renderer="public_moneyRenderer">总金额</div>
                        <div field="actualAmount" width="140" headerAlign="center" align="right" allowSort="false" renderer="public_moneyRenderer">实收金额</div>
                        <div field="dropAmount" width="140" headerAlign="center" align="right" allowSort="false" renderer="public_moneyRenderer">调整金额(拉货)</div>
                        <div field="settlementAmount" width="140" headerAlign="center" align="right" allowSort="false" renderer="public_moneyRenderer">结算金额</div>
                        <div field="cashierId" width="140" headerAlign="center" align="center" allowSort="false" data-options='{cacheName:"sysUser"}' renderer="commonRender">收银员</div>
                        <div field="openBillUserId" width="140" headerAlign="center" align="center" allowSort="false" data-options='{cacheName:"sysUser"}' renderer="commonRender">开单人</div>
                        <div field="openBillDate" width="140" headerAlign="center" align="center" allowSort="false" dateFormat="yyyy-MM-dd HH:mm:ss" renderer="ondayRenderer">开单日期</div>
                    </div>
                </div>
            </div>
        </div>





        <script type="text/javascript">
            mini.parse();
            let invoiceForm = new mini.Form("#invoiceForm");

            let grid = mini.get("datagrid1");

            let deliveryCustomerId = mini.get("deliveryCustomerId");
            let addBtn = mini.get("addBtn");
            let removeBtn = mini.get("removeBtn");

            let selectedBillDatagrid = mini.get("selectedBillDatagrid");

            let invoiceAmount = mini.get("invoiceAmount");
            let openInvoiceCompanyId = mini.get("openInvoiceCompanyId");
            let customerInvoiceId = mini.get("customerInvoiceId");
            let invoiceTitle = mini.get("invoiceTitle");
            let taxpayerIdentificationNumber = mini.get("taxpayerIdentificationNumber");
            let phoneNumber = mini.get("phoneNumber");
            let invoiceAddress = mini.get("invoiceAddress");
            let openAccountBankId = mini.get("openAccountBankId");
            let bankAccount = mini.get("bankAccount");
            let invoiceTypeId = mini.get("invoiceTypeId");
            let rateId = mini.get("rateId");
            let recipientName = mini.get("recipientName");
            let recipientPhone = mini.get("recipientPhone");
            let recipientAddress = mini.get("recipientAddress");



            let keyDeliveryCustomerId = mini.get("keyDeliveryCustomerId");
            let keyDeliveryCustomerName = mini.get("keyDeliveryCustomerName");
            let keyBillCode = mini.get("keyBillCode");
            let keyOpenBillStartDate = mini.get("keyOpenBillStartDate");
            let keyOpenBillEndDate = mini.get("keyOpenBillEndDate");


            // 定义已经选择的分单列表
            let selectedBillArray = [];

            let keyExcludeBillCodeIdArray = [];


            $(function (){
                let deliveryCustomerIdJsonData = commonRenderDropList("customer");
                deliveryCustomerId.load(deliveryCustomerIdJsonData);

                let openAccountBankIdJsonData =commonRenderDropList("bank");
                openAccountBankId.load(openAccountBankIdJsonData);

                let invoiceTypeIdJsonData = commonRenderSysDicDropListByKey("sysDic", "XT_DIC_INVOICE_TYPE");
                invoiceTypeId.load(invoiceTypeIdJsonData);

                let rateIdJsonData = commonRenderSysDicDropListByKey("sysDic", "XT_DIC_INVOICE_RATE");
                rateId.load(rateIdJsonData);

                let openInvoiceCompanyIdJsonData = commonRenderSysDicDropListByKey("sysDic", "XT_DIC_OPEN_INVOICE_COMPANY");
                openInvoiceCompanyId.load(openInvoiceCompanyIdJsonData);
            });

            /**
             * 设置底部统计样式
             * @param e
             */
            function summaryRight(e){
                e.cellStyle="text-align:right;color:red;font-size:18px;font-weight:bold";
            }

            /**
             * 发货人选择变化，用于加载对应的发货人的可开发票列表,如果只有一个选择项，则直接选择好并填充，如果是多个则让其选择，如果没有则给出不能选择分单的提示
             */
            function deliveryCustomerIdChange(e){
                let customerIdValue = e.value;
                if(public_isEmpty(customerIdValue)){
                    addBtn.set({enabled:false});
                    removeBtn.set({enabled:false});
                }
                else{
                    addBtn.set({enabled:true});
                    removeBtn.set({enabled:true});
                }
                // 如果换了发货人，数据需要清空

                // 换了发货人重新拉取一下应该排除的单号
                let ret = public_getServerData("${base}/pages/finance_manage/invoice_register/queryExcludeBill",{deliveryCustomerId:customerIdValue});
                if(ret.ok){
                    // 已经开发票的分单加入到排除列表
                    for(let obj of ret.data){
                        keyExcludeBillCodeIdArray.push(obj);
                    }

                }

                // 清空原来的信息
                emptyInvoiceAreaInfo();

                // 加载发票抬头信息
                let invoiceRet = public_getServerData("${base}/pages/customer_manage/invoice/queryInvoiceByCustomerId",{customerId:customerIdValue});
                if(!public_isEmpty(invoiceRet)){
                    // 重新绑定数据
                    customerInvoiceId.load(invoiceRet);
                    if(invoiceRet.length==1){
                        // 直接选择中这个对象
                        customerInvoiceId.select(0);
                        setInvoiceAreaValue(invoiceRet[0]);
                    }
                }

            }

            function customerInvoiceIdChange(e){
                let item = e.selected;
                setInvoiceAreaValue(item);
            }

            // 设置值
            function setInvoiceAreaValue(obj){
                invoiceTitle.setValue(obj.invoiceTitle);
                taxpayerIdentificationNumber.setValue(obj.taxpayerIdentificationNumber);
                phoneNumber.setValue(obj.phoneNumber);
                invoiceAddress.setValue(obj.invoiceAddress);
                openAccountBankId.setValue(obj.openAccountBankId);
                bankAccount.setValue(obj.bankAccount);
                invoiceTypeId.setValue(obj.invoiceTypeId);
                rateId.setValue(obj.rateId);
                recipientName.setValue(obj.recipientName);
                recipientPhone.setValue(obj.recipientPhone);
                recipientAddress.setValue(obj.recipientAddress);

            }

            // 清空值
            function emptyInvoiceAreaInfo(){

                invoiceAmount.setValue(0);

                customerInvoiceId.load();
                invoiceTitle.setValue();
                taxpayerIdentificationNumber.setValue();
                phoneNumber.setValue();
                invoiceAddress.setValue();
                openAccountBankId.setValue();
                bankAccount.setValue();
                invoiceTypeId.setValue();
                rateId.setValue();
                recipientName.setValue();
                recipientPhone.setValue();
                recipientAddress.setValue();

                // 清空原来的列表
                selectedBillArray.splice(0,selectedBillArray.length);
                // 清空绑定的 grid 数据
                selectedBillDatagrid.clearRows();
            }


            /**
             * 根据查询条件查询分单
             */
            function searchBill(){
                let form = new mini.Form("#queryForm");
                let data = form.getData(true);

                let keyExcludeBillCodeIds = "";

                // 这是原始要排除的
                for(let obj of keyExcludeBillCodeIdArray){
                    keyExcludeBillCodeIds += "'" + obj.id + "',";
                }

                // 这个是已经选择需要排除的
                for(let obj of selectedBillArray){
                    keyExcludeBillCodeIds += "'" + obj.id + "',";
                }

                if(keyExcludeBillCodeIds.length>0){
                    keyExcludeBillCodeIds = keyExcludeBillCodeIds.substr(0,keyExcludeBillCodeIds.length-1);
                    data.keyExcludeBillCodeIds = keyExcludeBillCodeIds;
                }
                grid.load(data);
            }

            function showSelectNativeBillPanel(){

                keyDeliveryCustomerId.setValue(deliveryCustomerId.getValue());
                keyDeliveryCustomerName.setValue(deliveryCustomerId.getText());

                searchBill();

                public_showModelAtPos("billSelectPanel", "center", "middle");
            }


            function saveSelect(){
                let selectedItems = grid.getSelecteds();
                if(selectedItems.length==0){
                    showAlert("请选择需要开取发票的分单!");
                    return;
                }

                // 把选择的对象加入到相应的选择列表中
                let tempSelectedBillArray = [];
                for(let obj of selectedItems){
                    let isExist = false;
                    for(let obj1 of selectedBillArray){
                        if(obj.id == obj1.id){
                            isExist = true;
                            break;
                        }
                    }
                    if(!isExist){
                        tempSelectedBillArray.push(obj);
                    }
                }
                // 加入到现有集合
                selectedBillArray.push(...tempSelectedBillArray);

                // 重新绑定数据
                rebindBillDatagrid();

                // 重新做一次查询操作
                searchBill();
            }

            /**
             * 重新绑定数据
             */
            function rebindBillDatagrid(){
                // 然后对外面的表进行重新绑定处理
                selectedBillDatagrid.clearRows();
                let totalInvoiceAmount = 0;
                for(let obj of selectedBillArray){
                    selectedBillDatagrid.addRow(obj);
                    totalInvoiceAmount += public_toNumber(obj.settlementAmount,0);
                }
                // 设置总金额
                invoiceAmount.setValue(public_round2(totalInvoiceAmount));
            }


            /**
             * 已选择分单列表中的对象做剔除操作
             */
            function removeNativeBill(){
                let selectedItems = selectedBillDatagrid.getSelecteds();
                if(selectedItems.length==0){
                    showAlert("请选择要剔除的分单!");
                    return;
                }
                // 根据 id 从selectedBillArray中移除相应的记录
                let tempSelectedBillArray = [];
                for(let obj of selectedBillArray){
                    let isExist = false;
                    for(let obj1 of selectedItems){
                        if(obj1.id == obj.id){
                            isExist = true;
                            break;
                        }
                    }

                    if(!isExist){
                        tempSelectedBillArray.push(obj);
                    }
                }

                selectedBillArray.splice(0,selectedBillArray.length,...tempSelectedBillArray);

                // 重新绑定
                rebindBillDatagrid();
            }

            /**
             * 保存发票信息
             */
            function saveInvoice(){
                invoiceForm.validate();
                if (invoiceForm.isValid() == false) {
                    return;
                }

                let invoiceFormData = invoiceForm.getData(true);

                let selectedBillDatagridData = selectedBillDatagrid.data;

                if(selectedBillDatagridData.length == 0){
                    showAlert("没有选择需要开票分单!");
                    return;
                }

                let detailPojoListArray = [];
                for(let obj of selectedBillDatagridData){
                    let newObj = {cwInvoiceRegisterId:"001",nativeBillId:obj.id};
                    detailPojoListArray.push(newObj);
                }


                let bean ={cwInvoiceRegisterPojo:invoiceFormData,detailPojoList:detailPojoListArray};

                mini.confirm(
                    "确定保存开票记录?",
                    "开票记录保存",
                    function(action) {
                        if (action == "ok") {
                            let ret = public_getServerData("${base}/pages/finance_manage/invoice_register/save",bean);
                            showAlert(ret.message,function (){
                                if(ret.ok){
                                    // 刷新当前页面
                                    window.location.reload();
                                }
                            });
                        }
                    });
            }
        </script>
    </body>
</html>